/**
 * 字典管理页面
 */
import React, { useState, useEffect } from 'react';
import { Table, Button, Space, Typography, Form, Input, Select, Modal, message, Popconfirm } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined } from '@ant-design/icons';
import { getDictionaryById, createDictionary, updateDictionary, deleteDictionary, searchDictionaries } from '../services/dictionaryService';
import { Dictionary } from '../types/dictionary';
import { PageResponse } from '../types/pageType';

const { Title } = Typography;
const { Option } = Select;

const DictionaryManagement: React.FC = () => {
    // 状态管理
    const [dictionaries, setDictionaries] = useState<Dictionary[]>([]);
    const [loading, setLoading] = useState<boolean>(false);
    const [total, setTotal] = useState<number>(0);
    const [currentPage, setCurrentPage] = useState<number>(1);
    const [pageSize, setPageSize] = useState<number>(10);
    const [isModalVisible, setIsModalVisible] = useState<boolean>(false);
    const [modalType, setModalType] = useState<'add' | 'edit'>('add');
    const [editingDictionary, setEditingDictionary] = useState<Dictionary | null>(null);
    const [searchForm] = Form.useForm();
    const [form] = Form.useForm();

    // 搜索条件
    const [searchParams, setSearchParams] = useState<{
        dictType?: string;
        dictCode?: string;
        enabled?: number;
    }>({});

    // 页面加载时获取字典数据
    useEffect(() => {
        fetchDictionaries();
    }, [currentPage, pageSize, searchParams]);

    // 获取字典数据
    const fetchDictionaries = async () => {
        setLoading(true);
        try {
            const response: PageResponse<Dictionary> = await searchDictionaries(
                searchParams.dictType,
                searchParams.dictCode,
                searchParams.enabled,
                currentPage,
                pageSize
            );
            setDictionaries(response.records);
            setTotal(response.total);
        } catch (error) {
            console.error('获取字典数据失败:', error);
            message.error('获取字典数据失败，请重试');
        } finally {
            setLoading(false);
        }
    };

    // 处理搜索
    const handleSearch = async () => {
        try {
            const values = await searchForm.validateFields();
            setSearchParams({
                dictType: values.dictType || undefined,
                dictCode: values.dictCode || undefined,
                enabled: values.enabled || undefined
            });
            setCurrentPage(1); // 重置到第一页
        } catch (error) {
            console.error('搜索参数验证失败:', error);
        }
    };

    // 重置搜索条件
    const handleReset = () => {
        searchForm.resetFields();
        setSearchParams({});
        setCurrentPage(1);
    };

    // 显示添加字典模态框
    const showAddModal = () => {
        setModalType('add');
        setEditingDictionary(null);
        form.resetFields();
        // 设置默认值类型为普通文本
        form.setFieldsValue({ dictValueType: 'text' });
        setIsModalVisible(true);
    };

    // 显示编辑字典模态框
    const showEditModal = async (id: number) => {
        setLoading(true);
        try {
            const dictionary = await getDictionaryById(id);
            setEditingDictionary(dictionary);

            // 判断值是否为JSON字符串
            let isJson = false;
            try {
                if (dictionary.dictValue) {
                    JSON.parse(dictionary.dictValue);
                    isJson = true;
                }
            } catch (error) {
                isJson = false;
            }

            // 设置表单值，并添加dictValueType字段
            form.setFieldsValue({
                ...dictionary,
                dictValueType: isJson ? 'json' : 'text'
            });

            setModalType('edit');
            setIsModalVisible(true);
        } catch (error) {
            console.error('获取字典详情失败:', error);
            message.error('获取字典详情失败，请重试');
        } finally {
            setLoading(false);
        }
    };

    // 处理表单提交
    const handleSubmit = async () => {
        try {
            const values = await form.validateFields();
            // 移除dictValueType字段，不发送到后端
            const { dictValueType, ...restValues } = values;
            const dictionaryData: Dictionary = {
                ...restValues,
                id: modalType === 'edit' && editingDictionary ? editingDictionary.id : undefined
            };

            if (modalType === 'add') {
                await createDictionary(dictionaryData);
                message.success('字典添加成功');
            } else {
                await updateDictionary(dictionaryData);
                message.success('字典更新成功');
            }

            setIsModalVisible(false);
            fetchDictionaries();
        } catch (error) {
            console.error('提交表单失败:', error);
            message.error('提交表单失败，请重试');
        }
    };

    // 处理删除字典
    const handleDelete = async (id: number) => {
        try {
            await deleteDictionary(id);
            message.success('字典删除成功');
            fetchDictionaries();
        } catch (error) {
            console.error('删除字典失败:', error);
            message.error('删除字典失败，请重试');
        }
    };

    // 表格列定义
    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',
            width: 80
        },
        {
            title: '字典类型编码',
            dataIndex: 'dictType',
            key: 'dictType'
        },
        {
            title: '字典项编码',
            dataIndex: 'dictCode',
            key: 'dictCode'
        },
        {
            title: '字典项名称',
            dataIndex: 'dictName',
            key: 'dictName'
        },
        {
            title: '字典项值',
            dataIndex: 'dictValue',
            key: 'dictValue'
        },
        {
            title: '状态',
            dataIndex: 'enabled',
            key: 'enabled',
            render: (enabled: number) => (
                <span>{enabled === 1 ? '启用' : '禁用'}</span>
            )
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            render: (time: Date) => (
                <span>{new Date(time).toLocaleString()}</span>
            )
        },
        {
            title: '操作',
            key: 'action',
            width: 150,
            render: (_: any, record: Dictionary) => (
                <Space size="middle">
                    <Button
                        type="primary"
                        icon={<EditOutlined />}
                        size="small"
                        onClick={() => showEditModal(record.id!)}
                    >
                        编辑
                    </Button>
                    <Popconfirm
                        title="确定要删除这个字典项吗?"
                        onConfirm={() => handleDelete(record.id!)}
                        okText="确定"
                        cancelText="取消"
                    >
                        <Button
                            type="default"
                            icon={<DeleteOutlined />}
                            size="small"
                        >
                            删除
                        </Button>
                    </Popconfirm>
                </Space>
            )
        }
    ];

    return (
        <div style={{ padding: 24 }}>
            <Title level={2}>字典管理</Title>

            {/* 搜索表单 */}
            <Form
                form={searchForm}
                layout="inline"
                style={{ marginBottom: 24 }}
            >
                <Form.Item name="dictType" label="字典类型编码">
                    <Input placeholder="请输入字典类型编码" />
                </Form.Item>
                <Form.Item name="dictCode" label="字典项编码">
                    <Input placeholder="请输入字典项编码" />
                </Form.Item>
                <Form.Item name="enabled" label="状态">
                    <Select placeholder="请选择状态">
                        <Option value={1}>启用</Option>
                        <Option value={0}>禁用</Option>
                    </Select>
                </Form.Item>
                <Form.Item>
                    <Space>
                        <Button
                            type="primary"
                            icon={<SearchOutlined />}
                            onClick={handleSearch}
                        >
                            搜索
                        </Button>
                        <Button onClick={handleReset}>重置</Button>
                    </Space>
                </Form.Item>
            </Form>

            {/* 添加按钮 */}
            <Button
                type="primary"
                icon={<PlusOutlined />}
                style={{ marginBottom: 16 }}
                onClick={showAddModal}
            >
                添加字典项
            </Button>

            {/* 字典列表 */}
            <Table
                columns={columns}
                dataSource={dictionaries}
                rowKey="id"
                loading={loading}
                pagination={{
                    current: currentPage,
                    pageSize: pageSize,
                    total: total,
                    showSizeChanger: true,
                    showTotal: (total) => `共 ${total} 条记录`,
                    pageSizeOptions: ['10', '20', '50']
                }}
                onChange={(pagination) => {
                    setCurrentPage(pagination.current!);
                    setPageSize(pagination.pageSize!);
                }}
            />

            {/* 添加/编辑字典模态框 */}
            <Modal
                title={modalType === 'add' ? '添加字典项' : '编辑字典项'}
                open={isModalVisible}
                onCancel={() => setIsModalVisible(false)}
                footer={[
                    <Button key="cancel" onClick={() => setIsModalVisible(false)}>
                        取消
                    </Button>,
                    <Button key="submit" type="primary" loading={loading} onClick={handleSubmit}>
                        {modalType === 'add' ? '添加' : '更新'}
                    </Button>
                ]}
            >
                <Form
                    form={form}
                    layout="vertical"
                    name="dictionary_form"
                >
                    <Form.Item
                        name="dictType"
                        label="字典类型编码"
                        rules={[{ required: true, message: '请输入字典类型编码' }]}
                    >
                        <Input placeholder="请输入字典类型编码" />
                    </Form.Item>

                    <Form.Item
                        name="dictCode"
                        label="字典项编码"
                        rules={[{ required: true, message: '请输入字典项编码' }]}
                    >
                        <Input placeholder="请输入字典项编码" />
                    </Form.Item>

                    <Form.Item
                        name="dictName"
                        label="字典项名称"
                        rules={[{ required: true, message: '请输入字典项名称' }]}
                    >
                        <Input placeholder="请输入字典项名称" />
                    </Form.Item>

                    <Form.Item
                        name="dictValueType"
                        label="值类型"
                        rules={[{ required: true, message: '请选择值类型' }]}
                    >
                        <Select placeholder="请选择值类型">
                            <Option value="text">普通文本</Option>
                            <Option value="json">JSON字符串</Option>
                        </Select>
                    </Form.Item>

                    <Form.Item
                        name="dictValue"
                        label="字典项值"
                        rules={[
                            { required: true, message: '请输入字典项值' },
                            ({ getFieldValue }) => ({
                                validator(_, value) {
                                    const dictValueType = getFieldValue('dictValueType');
                                    if (dictValueType === 'json' && value) {
                                        try {
                                            JSON.parse(value);
                                            return Promise.resolve();
                                        } catch (error) {
                                            return Promise.reject(new Error('请输入有效的JSON字符串'));
                                        }
                                    }
                                    return Promise.resolve();
                                },
                            }),
                        ]}
                    >
                        <Input
                            placeholder={
                                form.getFieldValue('dictValueType') === 'json'
                                    ? '请输入有效的JSON字符串' : '请输入字典项值'
                            }
                            showCount
                        />
                    </Form.Item>

                    <Form.Item
                        name="enabled"
                        label="状态"
                        rules={[{ required: true, message: '请选择状态' }]}
                    >
                        <Select placeholder="请选择状态">
                            <Option value={1}>启用</Option>
                            <Option value={0}>禁用</Option>
                        </Select>
                    </Form.Item>

                    {modalType === 'edit' && (
                        <Form.Item name="id" label="ID" hidden>
                            <Input />
                        </Form.Item>
                    )}
                </Form>
            </Modal>
        </div>
    );
};

export default DictionaryManagement;